package com.hxk.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 自旋锁
 *      自旋锁，就是尝试获取锁的线程不会立即阻塞，而是采用循环的方式尝试获取，自己在那一直循环获取，就像自旋一样，
 *  自旋锁的优点：
 *      减少线程切换的上下文开销
 *   自旋锁的缺点：
 *      有时一直循环对cpu消耗很大
 * java.util.concurrent.atomic.AtomicInteger的类的getAndIncrement底层实现就是CAS，而CAS底层就是自旋锁思想
 *
 * 本case手写一个自旋锁
 */
public class SpinLockCase {

    public static void main(String[] args) {

        MyLock myLock = new MyLock();

        new Thread(()->{
            myLock.lock();
            try {
                TimeUnit.SECONDS.sleep(5);//等待5秒让B线程进入
            } catch (Exception e) {
                e.printStackTrace();
            }
            myLock.unlock();
        },"A").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (Exception e) {
            e.printStackTrace();
        }

        new Thread(()->{
            myLock.lock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            myLock.unlock();
        },"B").start();
    }
}

class MyLock{

    AtomicReference<Thread> ar = new AtomicReference<>();

    public void lock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "\t" + " come in ...");
        while (!ar.compareAndSet(null, thread)) { }//自旋锁
    }

    public void unlock(){
        Thread thread = Thread.currentThread();
        ar.compareAndSet(thread, null);
        System.out.println(Thread.currentThread().getName() + "\t" + " unlock ...");
    }
}
